package com.ls.io.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.List;

public class NIOServer {


    public static void main(String[] args) throws IOException {
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.bind(new InetSocketAddress(8088));
        serverSocketChannel.configureBlocking(false);

        ByteBuffer byteBuffer = ByteBuffer.allocateDirect(1024);

        List<SocketChannel> clients = new ArrayList<>();

        ByteBuffer data = ByteBuffer.wrap("hello, i am server\n".getBytes());

        while (true){
            SocketChannel socketChannel = serverSocketChannel.accept();

            if(socketChannel != null){
                socketChannel.configureBlocking(false);
                clients.add(socketChannel);
            }else{
//                System.out.println("no client accept");
            }


            List<SocketChannel> removes = new ArrayList<>();
            for (SocketChannel client : clients) {
                try {
                    int pos = client.read(byteBuffer);
                    if(pos > 0){
                        byteBuffer.flip();
                        byte[] d = new byte[byteBuffer.limit()];
                        byteBuffer.get(d);
                        System.out.println(new String(d));
                        byteBuffer.clear();

                        client.write(data);
                        data.flip();
                    }else{
//                        System.out.println("no read data from client");
                    }
                }catch (Exception e){
                    removes.add(client);
                    e.printStackTrace();
                }
            }
            clients.removeAll(removes);
        }

    }

}
